package com.oscar.ehome;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;

import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.oscar.ehome.base.AppManager;
import com.oscar.ehome.base.activity.BasesActivity;
import com.oscar.ehome.bean.pagebean.DiaoChaInfo;
import com.oscar.ehome.presenter.BasePresenter;
import com.oscar.ehome.presenter.WeclomePresenter;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.view.loginview.LoginActivity;
import com.oscar.ehome.view.pageview.view.DiaoChaView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by juxing
 * author: SunHaoZhao
 * date: On 2018/1/16
 */

public class DiaoChaActivity extends BasesActivity implements DiaoChaView {
     LinearLayout test_layout;

    //答案列表
    private List<DiaoChaInfo.QnQuestionList.qnqOptionList> the_answer_list;
    //问题列表
    private List<DiaoChaInfo.QnQuestionList> the_quesition_list;
    //问题所在的View
     View que_view;
    //答案所在的View
     View ans_view;
    private LayoutInflater xInflater;
     DiaoChaInfo diaoChaInfo;
    Button button;
    //下面这两个list是为了实现点击的时候改变图片，因为单选多选时情况不一样，为了方便控制
    //存每个问题下的imageview
    private ArrayList<ArrayList<ImageView>> imglist = new ArrayList<>();
    //存每个答案的imageview
    private ArrayList<ImageView> imglist2;
    WeclomePresenter presenter;
    String token = "";
    RelativeLayout basetitle_bar;
    private long mExitTime;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wenjuandiaocha);
        xInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        basetitle_bar =  findViewById(R.id.basetitle_bar);
        //假数据
        initView();
        //提交按钮
         button =  findViewById(R.id.quesiton_tj);

    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }


    private void initDate() {
        showLoading();
        //假数据
        // TODO Auto-generated method stub
        if (isNetWork()) {

            presenter.getDiaochaInfo(token);
        }
    }

    /**
     * 判断是否有网
     */
    public boolean isNetWork() {

            return CommonUtils.isNetConn(this);

    }

    private void initView() {
        basetitle_bar.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(DiaoChaActivity.this).getSystemConfig().getColor()));
        token = SystemConfigFactory.getInstance(DiaoChaActivity.this).getSystemConfig().getToken();
        presenter = new WeclomePresenter(this);
        initDate();
    }


    @Override
    public void getDiaocharesult(DiaoChaInfo result) {
        dismissLoading();
        if (result != null && !result.equals("")) {
            diaoChaInfo = result;
            //这是要把问题的动态布局加入的布局
            test_layout =  findViewById(R.id.lly_test);
            TextView page_txt = findViewById(R.id.title_topbar);
            TextView huanyingyu= findViewById(R.id.huanyingyu);
            TextView zhidaoyu=findViewById(R.id.zhidaoyu);
            button.setOnClickListener(new submitOnClickListener(diaoChaInfo));
            page_txt.setText("调查问卷");
            huanyingyu.setText(diaoChaInfo.getContent());
            zhidaoyu.setText(diaoChaInfo.getRemarks());
            //获得问题即第二层的数据
            the_quesition_list = diaoChaInfo.getQnQuestionList();
            //根据第二层问题的多少，来动态加载布局
            for (int i = 0; i < the_quesition_list.size(); i++) {
                que_view = xInflater.inflate(R.layout.quesition_layout, null);
                TextView txt_que = que_view.findViewById(R.id.txt_question_item);
                //这是第三层布局要加入的地方
                LinearLayout add_layout =  que_view.findViewById(R.id.lly_answer);
                //判断单选-多选来实现后面是*号还是*多选，

                txt_que.setText((i + 1) + "、" + the_quesition_list.get(i).getTitle());
                //获得答案即第三层数据

                the_quesition_list.get(i).setIshuida("false");
                if (the_quesition_list.get(i).getQnqList() != null && !the_quesition_list.get(i).getQnqList().equals("")
                        && the_quesition_list.get(i).getQnqList().size() > 0) {
                    the_answer_list = the_quesition_list.get(i).getQnqList();
                    imglist2 = new ArrayList<>();
                    for (int j = 0; j < the_answer_list.size(); j++) {
                        diaoChaInfo.getQnQuestionList().get(i).getQnqList().get(j).setIscheak("false");
                        ans_view = xInflater.inflate(R.layout.xuanxiang, null);
                        TextView txt_ans =  ans_view.findViewById(R.id.txt_answer_item);
                        ImageView image =  ans_view.findViewById(R.id.image);
                        View line_view = ans_view.findViewById(R.id.vw_line);
                        if (j == the_answer_list.size() - 1) {
                            //最后一条答案下面不要线是指布局的问题
                            line_view.setVisibility(View.GONE);
                        }
                        imglist2.add(image);
                        txt_ans.setText(the_answer_list.get(j).getTitle());
          //              LinearLayout lly_answer_size = ans_view.findViewById(R.id.lly_answer_size);
                        LinearLayout lly_answer_size=ans_view.findViewById(R.id.lly_answer_size);
                        lly_answer_size.setOnClickListener(new answerItemOnClickListener(i, j, the_answer_list, txt_ans));
                        add_layout.addView(ans_view);
                    }
                } else {
                    ans_view = xInflater.inflate(R.layout.xuanxiang,null);
                    TextView txt_ans =  ans_view.findViewById(R.id.txt_answer_item);
                    ImageView image =  ans_view.findViewById(R.id.image);
                    EditText edit =  ans_view.findViewById(R.id.wendaedit);
                    View line_view = ans_view.findViewById(R.id.vw_line);
                    image.setVisibility(View.GONE);
                    txt_ans.setVisibility(View.GONE);
                    line_view.setVisibility(View.GONE);
                    edit.setVisibility(View.VISIBLE);
                    LinearLayout lly_answer_size = (LinearLayout) ans_view.findViewById(R.id.lly_answer_size);
                    lly_answer_size.setVisibility(View.GONE);
                    edit.addTextChangedListener(new EditChangedListener(i, the_answer_list));
                    add_layout.setBackground(null);
                    add_layout.addView(ans_view);


                }
            /*for(int r=0; r<imglist2.size();r++){
                Log.e("---", "imglist2--------"+imglist2.get(r));
            }*/

                imglist.add(imglist2);

                test_layout.addView(que_view);
            }

        }
    }

    @Override
    public void putshuju(String result) {
        ToastUtil.show(this,"提交成功");
        Intent in=new Intent();
        in.setClass(this, MainActivity.class);
        startActivity(in);
        finish();
    }

    @Override
    public void erroy() {
        dismissLoading();

        ToastUtil.show(this, getString(R.string.erry));

    }

    @Override
    public void erry(String result) {
        dismissLoading();

        ToastUtil.show(this, result);

        if (result.contains("过期")) {
            getSharedPreferences("appbase", Context.MODE_PRIVATE).edit().clear().commit();
            SystemConfigFactory.getInstance(this).getSystemConfig().SetLogin(false);
            SystemConfigFactory.getInstance(this).getSystemConfig().setIsFirst(true);
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
    }

   private class EditChangedListener implements TextWatcher {
        private int i;


         List<DiaoChaInfo.QnQuestionList.qnqOptionList> the_answer_lists;

        private EditChangedListener(int i, List<DiaoChaInfo.QnQuestionList.qnqOptionList> the_answer_list) {
            this.i = i;

            this.the_answer_lists = the_answer_list;


        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() > 0) {
                the_quesition_list.get(i).setIshuida("ture");
                the_quesition_list.get(i).setAnswer(s.toString());
            } else {
                the_quesition_list.get(i).setIshuida("false");
            }
        }
    }

    private class answerItemOnClickListener implements View.OnClickListener {
        private int i;
        private int j;
        TextView txt;
        private List<DiaoChaInfo.QnQuestionList.qnqOptionList> the_answer_lists;

        private answerItemOnClickListener(int i, int j, List<DiaoChaInfo.QnQuestionList.qnqOptionList> the_answer_list, TextView text) {
            this.i = i;
            this.j = j;
            this.the_answer_lists = the_answer_list;
            this.txt = text;

        }

        //实现点击选项后改变选中状态以及对应图片
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            //判断当前问题是单选还是多选
            if (the_quesition_list.get(i).getType().equals("1")) {
                //单选
                for (int z = 0; z < the_answer_lists.size(); z++) {
                    the_answer_lists.get(z).setIscheak("false");
                    imglist.get(i).get(z).setImageResource(R.mipmap.weixuantubiao);
                }
                if (the_answer_lists.get(j).getIscheak().equals("false")) {
                    //如果当前未被选中
                    imglist.get(i).get(j).setImageResource(R.mipmap.xuanzhongtubiao);
                    the_answer_lists.get(j).setIscheak("ture");
                    the_quesition_list.get(i).setAnswer(the_answer_lists.get(j).getId());
                    the_quesition_list.get(i).setIshuida("ture");
                }

            }
            //判断当前选项是否选中


        }

    }





   private class submitOnClickListener implements View.OnClickListener {
        private DiaoChaInfo page;
        private Gson gson;
        private GsonBuilder builder;
        private String jsonTest;
        private submitOnClickListener(DiaoChaInfo page) {
            this.page = page;
        }

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            //判断是否答完题
            boolean isState = true;

            for (int i = 0; i < the_quesition_list.size(); i++) {
                the_answer_list = the_quesition_list.get(i).getQnqList();
                //判断是否有题没答完
                if (the_quesition_list.get(i).getIshuida().equals("false")) {
                    Toast.makeText(getApplicationContext(), "您第" + (i + 1) + "题没有回答", Toast.LENGTH_LONG).show();

                    isState = false;
                    break;
                }

            }
            if (isState) {
                if(IsDoubClick()){
                    builder=new GsonBuilder();
                    gson=builder.create();
                    jsonTest= gson.toJson(page, DiaoChaInfo.class);

                    presenter.putshuju(jsonTest,token);
                }else{
                    ToastUtil.show(getApplicationContext(),"正在提交，请稍等");
                }


            }

        }
    }
    public static long lastTime;
    public boolean IsDoubClick() {
        boolean flag = false;
        long time = System.currentTimeMillis() - lastTime;
        if(time > 2000)  {
            flag = true;
        }
        lastTime = System.currentTimeMillis();
        return flag;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {

                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
                AppManager appManager = AppManager.getAppManager();
                appManager.finishAllActivity();
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

//    @Override
//    public WeclomePresenter createPresenter() {
//        presenter = new PagePresenter(this);
//        return presenter;
//    }

}



